package ua.in.iticket.addressbook.userinterface;

import java.util.*;

/**
 * Created by ivanov-av
 * 14.02.14 9:42.
 */
public class Menu {
    private List<MenuItem> items;

    public Menu() {
        items = new ArrayList<MenuItem>();
        addItem("Help",MenuConfig.MENU_HELP_ACTION, "Print help");
        addItem("Exit",MenuConfig.MENU_EXIT_ACTION, "Exit");
    }

    public void addItem(MenuItem item) {
        items.add(item);
    }

    public void addItem(String itemName, Integer itemAction,String itemDescr) {
        items.add(new MenuItem(itemName,itemAction, itemDescr));
    }

    public void printMenu() {
        Collections.sort(items);
        Iterator<MenuItem> itemIterator = items.iterator();
        while (itemIterator.hasNext()) {
            MenuItem item = itemIterator.next();
            if (item.isEnabled()) {
                System.out.print(new StringBuilder().append(" ").append(item.getItemAction()).append("-").append(item.getItemName()).toString());
            }
        }
        System.out.println("");
    }

    public void printMenuHelp() {
        Collections.sort(items);
        Iterator<MenuItem> itemIterator = items.iterator();
        while (itemIterator.hasNext()) {
            MenuItem item = itemIterator.next();
            if (item.isEnabled()) {
                System.out.println(new StringBuilder().append(" ").append(item.getItemName()).append(": ").append(item.getItemDescription()).toString());
            }
        }
        System.out.println("");
    }

    protected boolean isAllowedAction(Integer action) {
        boolean ret = false;
        Iterator<MenuItem> itemIterator = items.iterator();
        while (itemIterator.hasNext()) {
            MenuItem item = itemIterator.next();
            if ((item.getItemAction() == action) && item.isEnabled()) {
                ret = true;
                break;
            }
        }
        if (action == MenuConfig.MENU_HELP_ACTION) ret = false;
        return ret;
    }

    public Integer getAction(String promt) {
        Integer action = -1;
        Scanner scanner = new Scanner(System.in);
        String error = "";
        do {
            System.out.print(error + promt + ": ");
            action = scanner.nextInt();
            if (action == MenuConfig.MENU_HELP_ACTION) {
                printMenuHelp();
                printMenu();
            }
        } while (!isAllowedAction(action));
        return action;
    }

    public Integer getAction() {
        return getAction("Enter the selected action");
    }

    public void sort() {
        Collections.sort(items);
    }
}
